const express = require('express');
const router = express.Router();

const ChatGroup = require('../models/ChatGroupPrisma');
const GroupMember = require('../models/GroupMemberPrisma');
const Message = require('../models/MessagePrisma');
const UserPrisma = require('../models/UserPrisma');
const ContactViewPrisma = require('../models/ContactViewPrisma');
const { prisma } = require('../config/prisma');
const { authenticateToken, optionalAuth } = require('../middleware/auth');
const { autoJoinGroup, optionalAutoJoinGroup } = require('../middleware/autoJoinGroup');
const ResponseHelper = require('../utils/response');
const Validator = require('../utils/validator');
const WechatOfficialService = require('../utils/WechatOfficialService');
const IpLocationService = require('../utils/IpLocationService');
const UserLocationHelper = require('../utils/userLocation');

class ChatQuotaError extends Error {
  constructor(message, data = null) {
    super(message);
    this.name = 'ChatQuotaError';
    this.data = data;
  }
}

const ensureChatQuota = async (userId, plannedMessages = 1) => {
  const safePlannedMessages = Math.max(0, parseInt(plannedMessages, 10) || 0);
  if (safePlannedMessages === 0) {
    return { mode: 'free', remainingAfterSend: Infinity };
  }

  const chatConfig = await ContactViewPrisma.getChatMessageConfig();

  if (chatConfig.chat_message_mode === 'free') {
    const dailyLimit = chatConfig.chat_free_daily_limit;
    if (dailyLimit <= 0) {
      throw new ChatQuotaError('当前为免费模式，但每日可发送条数为 0，暂时无法发送消息', {
        chat_quota: {
          mode: 'free',
          remaining: 0,
          dailyLimit,
          required: safePlannedMessages
        }
      });
    }

    const sentToday = await Message.getUserDailyMessageCount(userId);
    const remaining = dailyLimit - sentToday;
    const quotaData = {
      chat_quota: {
        mode: 'free',
        remaining: Math.max(0, remaining),
        dailyLimit,
        required: safePlannedMessages
      }
    };

    if (remaining <= 0) {
      throw new ChatQuotaError(`今日免费聊天次数已用完（每日上限 ${dailyLimit} 条）`, quotaData);
    }

    if (safePlannedMessages > remaining) {
      throw new ChatQuotaError(`今日仅剩 ${remaining} 条免费消息额度，无法发送 ${safePlannedMessages} 条消息`, quotaData);
    }

    return {
      mode: 'free',
      dailyLimit,
      remainingAfterSend: remaining - safePlannedMessages
    };
  }

  try {
    await UserPrisma.reduceChatCredits(userId, safePlannedMessages);
    return {
      mode: 'paid',
      creditsConsumed: safePlannedMessages
    };
  } catch (error) {
    if (error.message === '聊天消息额度不足') {
      throw new ChatQuotaError('聊天消息额度不足，请购买聊天套餐', {
        chat_quota: {
          mode: 'paid',
          remaining: 0,
          required: safePlannedMessages
        }
      });
    }
    throw error;
  }
};

const handleQuotaError = (error, res) => {
  if (error instanceof ChatQuotaError) {
    return ResponseHelper.forbidden(res, error.message, error.data || null);
  }
  throw error;
};

/**
 * 异步调度微信公众平台群聊推送
 * @param {Object} options
 * @param {number|bigint|string} options.userId 发送者ID
 * @param {string} options.senderNickname 发送者昵称
 * @param {string} options.content 消息内容
 * @param {string} [options.region] 地区/群组名称
 * @param {string} [options.logTag] 日志前缀
 * @param {string} [options.targetName] 目标群日志名称
 */
const scheduleGroupWechatPush = ({
  userId,
  senderNickname,
  content,
  region,
  logTag = '📱 [公众号推送-分群]',
  targetName
}) => {
  const trimmedContent = typeof content === 'string' ? content.trim() : '';
  if (!trimmedContent) {
    console.log(`${logTag} 消息内容为空，跳过推送`);
    return;
  }

  const normalizedUserId = typeof userId === 'bigint' ? userId : BigInt(userId);

  setImmediate(async () => {
    try {
      console.log(`${logTag} 开始执行推送逻辑...`);
      console.log(`${logTag} 发送者ID:`, String(userId));
      if (targetName) {
        console.log(`${logTag} 目标群组:`, targetName);
      }

      const provinceKey = IpLocationService.mapRegionToProvinceKey(region || targetName) || '全国';
      const shouldFilterByProvince = provinceKey !== '全国';
      console.log(`${logTag} 目标省份Key:`, provinceKey);

      const subscribedUsers = await prisma.users.findMany({
        where: {
          wechat_official_subscribed: true,
          wechat_official_openid: { not: null },
          wechat_notification_enabled: true,
          id: { not: normalizedUserId }
        },
        select: {
          id: true,
          wechat_official_openid: true,
          nickname: true,
          last_known_province: true,
          last_known_ip: true
        }
      });

      console.log(`${logTag} 查询到${subscribedUsers.length}个符合条件的用户（未筛选）`);
      subscribedUsers.forEach(u => {
        console.log(`  - 用户ID: ${u.id}, OpenID: ${u.wechat_official_openid}, 昵称: ${u.nickname || '未知'}, 省份: ${u.last_known_province || '未记录'}, IP: ${u.last_known_ip || '未知'}`);
      });

      const filteredUsers = shouldFilterByProvince
        ? subscribedUsers.filter(u => {
            const userProvinceKey = IpLocationService.toProvinceKey(u.last_known_province);
            return userProvinceKey && userProvinceKey === provinceKey;
          })
        : subscribedUsers;

      console.log(`${logTag} 省份筛选后剩余 ${filteredUsers.length} 个用户`);

      if (filteredUsers.length > 0) {
        const openidList = filteredUsers
          .map(u => u.wechat_official_openid)
          .filter(Boolean);

        console.log(`${logTag} 准备向${openidList.length}个用户推送群聊消息通知`);
        console.log(`${logTag} 消息内容: ${trimmedContent}`);

        const pushResult = await WechatOfficialService.batchSendGroupMessageAlert(
          openidList,
          {
            senderName: senderNickname || '群友',
            content: trimmedContent,
            region: provinceKey
          }
        );

        console.log(`${logTag} 推送结果:`, pushResult);
      } else {
        console.log(`${logTag} 没有符合条件的用户需要推送公众号通知`);
      }
    } catch (pushError) {
      console.error(`${logTag} 推送失败:`, pushError);
      console.error(`${logTag} 错误堆栈:`, pushError.stack);
    }
  });
};

/**
 * 获取群组列表（公开接口，用于展示）
 * GET /api/v1/chat/groups
 */
router.get('/groups', async (req, res) => {
  try {
    const { page = 1, pageSize = 20 } = req.query;
    
    const result = await ChatGroup.getList({
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    });

    ResponseHelper.success(res, result, '获取群组列表成功');
  } catch (error) {
    console.error('获取群组列表错误:', error);
    ResponseHelper.serverError(res, '获取群组列表失败', error);
  }
});

/**
 * 获取用户所在的群组
 * GET /api/v1/chat/my-groups
 */
router.get('/my-groups', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const groups = await GroupMember.getUserGroups(userId);

    ResponseHelper.success(res, groups, '获取我的群组成功');
  } catch (error) {
    console.error('获取我的群组错误:', error);
    ResponseHelper.serverError(res, '获取我的群组失败', error);
  }
});

/**
 * 获取群组详情（不需要加入群组，仅查看群组信息）
 * GET /api/v1/chat/groups/:id
 */
router.get('/groups/:id', async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);

    const group = await ChatGroup.findByIdWithMembers(groupId);
    if (!group) {
      return ResponseHelper.notFound(res, '群组不存在');
    }

    ResponseHelper.success(res, group.toJSON(), '获取群组详情成功');
  } catch (error) {
    console.error('获取群组详情错误:', error);
    ResponseHelper.serverError(res, '获取群组详情失败', error);
  }
});

/**
 * 获取群组统计信息
 * GET /api/v1/chat/groups/:id/stats
 */
router.get('/groups/:id/stats', async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);

    // 检查群组是否存在
    const group = await ChatGroup.findById(groupId);
    if (!group) {
      return ResponseHelper.notFound(res, '群组不存在');
    }

    // 获取群组成员总数
    const memberCount = await ChatGroup.getMemberCount(groupId);

    // 获取日活跃用户统计
    const dailyStats = await Message.getGroupDailyActiveStats(groupId);

    const stats = {
      memberCount,
      dailyActiveUsers: dailyStats.dailyActiveUsers
    };

    ResponseHelper.success(res, stats, '获取群组统计成功');
  } catch (error) {
    console.error('获取群组统计错误:', error);
    ResponseHelper.serverError(res, '获取群组统计失败', error);
  }
});

/**
 * 加入群组
 * POST /api/v1/chat/groups/:id/join
 */
router.post('/groups/:id/join', authenticateToken, async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);
    const userId = req.user.id;

    // 检查群组是否存在
    const group = await ChatGroup.findById(groupId);
    if (!group) {
      return ResponseHelper.notFound(res, '群组不存在');
    }

    // 检查是否已经是成员
    const existingMember = await GroupMember.findByGroupAndUser(groupId, userId);
    if (existingMember) {
      return ResponseHelper.error(res, '您已经是该群组成员', 400);
    }

    // 添加成员
    const member = await GroupMember.create({
      group_id: groupId,
      user_id: userId,
      role: 'member'
    });

    // 创建系统消息
    const userNickname = req.user.nickname || `用户${userId}`;
    await Message.createSystemMessage(groupId, `${userNickname} 加入了群聊`);

    ResponseHelper.success(res, member.toJSON(), '加入群组成功');
  } catch (error) {
    console.error('加入群组错误:', error);
    ResponseHelper.serverError(res, '加入群组失败', error);
  }
});

/**
 * 退出群组
 * POST /api/v1/chat/groups/:id/leave
 */
router.post('/groups/:id/leave', authenticateToken, async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);
    const userId = req.user.id;

    // 检查是否是群组成员
    const member = await GroupMember.findByGroupAndUser(groupId, userId);
    if (!member) {
      return ResponseHelper.error(res, '您不是该群组成员', 400);
    }

    // 移除成员
    const removed = await GroupMember.remove(groupId, userId);
    if (!removed) {
      return ResponseHelper.error(res, '退出群组失败', 400);
    }

    // 创建系统消息
    const userNickname = req.user.nickname || `用户${userId}`;
    await Message.createSystemMessage(groupId, `${userNickname} 退出了群聊`);

    ResponseHelper.success(res, null, '退出群组成功');
  } catch (error) {
    console.error('退出群组错误:', error);
    ResponseHelper.serverError(res, '退出群组失败', error);
  }
});

/**
 * 获取群组成员列表（公开接口，不需要加入群组）
 * GET /api/v1/chat/groups/:id/members
 */
router.get('/groups/:id/members', async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);
    const { page = 1, pageSize = 50 } = req.query;

    // 检查群组是否存在
    const group = await ChatGroup.findById(groupId);
    if (!group) {
      return ResponseHelper.notFound(res, '群组不存在');
    }

    const result = await GroupMember.getGroupMembers(groupId, {
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    });

    ResponseHelper.success(res, result, '获取群组成员成功');
  } catch (error) {
    console.error('获取群组成员错误:', error);
    ResponseHelper.serverError(res, '获取群组成员失败', error);
  }
});

/**
 * 发送消息
 * POST /api/v1/chat/groups/:id/messages
 */
router.post('/groups/:id/messages', authenticateToken, autoJoinGroup, async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);
    const userId = req.user.id;
    const { content, message_type = 'text' } = req.body;
    const trimmedContent = typeof content === 'string' ? content.trim() : '';

    // console.log('[调试] /groups/:id/messages 收到消息', { groupId, userId: String(userId) });

    // 验证输入
    if (!trimmedContent) {
      return ResponseHelper.validationError(res, ['消息内容不能为空']);
    }

    // 检查用户是否被禁言
    const isBanned = await UserPrisma.isChatBanned(userId);
    if (isBanned) {
      return ResponseHelper.forbidden(res, '您已被禁言，无法发送消息');
    }

    try {
      await ensureChatQuota(userId, 1);
    } catch (error) {
      return handleQuotaError(error, res);
    }

    // 通过autoJoinGroup中间件，用户已经自动加入群组

    // 更新用户定位信息
    const { user: refreshedUser } = await UserLocationHelper.updateUserLocationFromRequest(req, req.user);
    if (refreshedUser) {
      req.user = refreshedUser;
    }

    // 创建消息
    const message = await Message.create({
      group_id: groupId,
      sender_id: userId,
      message_type,
      content: trimmedContent
    });

    // 获取完整的消息信息（包含发送者信息）
    const fullMessage = await Message.findById(message.id);
    const messageData = {
      ...fullMessage.toJSON(),
      sender: {
        id: userId.toString(),
        nickname: req.user.nickname || '未知用户',
        avatar_url: req.user.avatar_url
      }
    };

    const targetGroup = await ChatGroup.findById(groupId);

    ResponseHelper.success(res, messageData, '发送消息成功');

    scheduleGroupWechatPush({
      userId,
      senderNickname: req.user.nickname,
      content: trimmedContent,
      region: targetGroup?.group_name,
      logTag: '📱 [公众号推送-分群]',
      targetName: targetGroup?.group_name || `群组ID:${groupId}`
    });
  } catch (error) {
    console.error('发送消息错误:', error);

    if (error.message === '聊天消息额度不足') {
      return ResponseHelper.forbidden(res, '聊天消息额度不足，请购买聊天套餐');
    }

    ResponseHelper.serverError(res, '发送消息失败', error);
  }
});

/**
 * 获取群组消息列表（支持未登录用户查看）
 * GET /api/v1/chat/groups/:id/messages
 */
router.get('/groups/:id/messages', optionalAuth, optionalAutoJoinGroup, async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);
    const { page = 1, pageSize = 50, lastMessageId } = req.query;

    // 通过optionalAutoJoinGroup中间件，已登录用户已经自动加入群组

    const result = await Message.getGroupMessages(groupId, {
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      lastMessageId: lastMessageId ? parseInt(lastMessageId) : undefined
    });

    ResponseHelper.success(res, result, '获取消息列表成功');
  } catch (error) {
    console.error('获取消息列表错误:', error);
    ResponseHelper.serverError(res, '获取消息列表失败', error);
  }
});

/**
 * 获取新消息（轮询接口，支持未登录用户查看）
 * GET /api/v1/chat/groups/:id/new-messages
 */
router.get('/groups/:id/new-messages', optionalAuth, optionalAutoJoinGroup, async (req, res) => {
  try {
    const groupId = parseInt(req.params.id);
    const { lastMessageId = 0 } = req.query;

    // 通过optionalAutoJoinGroup中间件，已登录用户已经自动加入群组

    const newMessages = await Message.getNewMessages(groupId, parseInt(lastMessageId));

    ResponseHelper.success(res, newMessages, '获取新消息成功');
  } catch (error) {
    console.error('获取新消息错误:', error);
    ResponseHelper.serverError(res, '获取新消息失败', error);
  }
});

// ==================== 全国总群相关接口 ====================

/**
 * 获取所有群组的合并消息列表（全国总群功能）
 * GET /api/v1/chat/all-groups/messages
 */
router.get('/all-groups/messages', optionalAuth, async (req, res) => {
  try {
    const { page = 1, pageSize = 50, lastMessageId } = req.query;

    const result = await Message.getAllGroupsMessages({
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      lastMessageId: lastMessageId ? parseInt(lastMessageId) : undefined
    });

    ResponseHelper.success(res, result, '获取全国总群消息列表成功');
  } catch (error) {
    console.error('获取全国总群消息列表错误:', error);
    ResponseHelper.serverError(res, '获取全国总群消息列表失败', error);
  }
});

/**
 * 获取所有群组的新消息（全国总群轮询接口）
 * GET /api/v1/chat/all-groups/new-messages
 */
router.get('/all-groups/new-messages', optionalAuth, async (req, res) => {
  try {
    const { lastMessageId = 0 } = req.query;

    const newMessages = await Message.getAllGroupsNewMessages(parseInt(lastMessageId));

    ResponseHelper.success(res, newMessages, '获取全国总群新消息成功');
  } catch (error) {
    console.error('获取全国总群新消息错误:', error);
    ResponseHelper.serverError(res, '获取全国总群新消息失败', error);
  }
});

/**
 * 获取所有群组的汇总统计（全国总群统计）
 * GET /api/v1/chat/all-groups/stats
 */
router.get('/all-groups/stats', async (req, res) => {
  try {
    const stats = await Message.getAllGroupsStats();
    ResponseHelper.success(res, stats, '获取全国总群统计成功');
  } catch (error) {
    console.error('获取全国总群统计错误:', error);
    ResponseHelper.serverError(res, '获取全国总群统计失败', error);
  }
});

/**
 * 获取所有群组的成员列表（去重，全国总群用）
 * GET /api/v1/chat/all-groups/members
 */
router.get('/all-groups/members', async (req, res) => {
  try {
    const { page = 1, pageSize = 50 } = req.query;

    const result = await GroupMember.getAllGroupsMembers({
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    });

    ResponseHelper.success(res, result, '获取全国总群成员成功');
  } catch (error) {
    console.error('获取全国总群成员错误:', error);
    ResponseHelper.serverError(res, '获取全国总群成员失败', error);
  }
});

/**
 * 向指定群组发送消息（新的地区选择发送功能）
 * POST /api/v1/chat/groups/send-to-selected
 */
router.post('/groups/send-to-selected', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { content, message_type = 'text', group_id } = req.body;
    const trimmedContent = typeof content === 'string' ? content.trim() : '';

    console.log('[调试] /groups/:id/messages 收到消息', { group_id, userId: String(userId) });

    // 验证输入
    if (!trimmedContent) {
      return ResponseHelper.validationError(res, ['消息内容不能为空']);
    }

    if (!group_id) {
      return ResponseHelper.validationError(res, ['请选择要发送的群组']);
    }

    // 检查用户是否被禁言
    const isBanned = await UserPrisma.isChatBanned(userId);
    if (isBanned) {
      return ResponseHelper.forbidden(res, '您已被禁言，无法发送消息');
    }

    // 验证群组是否存在
    const group = await ChatGroup.findById(group_id);
    if (!group) {
      return ResponseHelper.notFound(res, '选择的群组不存在');
    }

    try {
      await ensureChatQuota(userId, 1);
    } catch (error) {
      return handleQuotaError(error, res);
    }

    // 自动加入群组（如果尚未加入）
    try {
      // 先检查是否已经是群组成员
      const existingMember = await GroupMember.findByGroupAndUser(group_id, userId);
      if (!existingMember) {
        await GroupMember.create({
          group_id: group_id,
          user_id: userId,
          role: 'member'
        });
        console.log(`用户 ${userId} 已自动加入群组 ${group_id}`);
      }
    } catch (error) {
      // 数据库连接失败或其他错误，记录警告但不阻止发送消息
      console.warn(`自动加入群组 ${group_id} 失败:`, error.message);
      // 继续执行，不让自动加入群组的失败阻止消息发送
    }

    // 更新用户定位信息
    const { user: refreshedUser } = await UserLocationHelper.updateUserLocationFromRequest(req, req.user);
    if (refreshedUser) {
      req.user = refreshedUser;
    }

    // 发送消息到指定群组
    const message = await Message.create({
      group_id: group_id,
      sender_id: userId,
      message_type,
      content: trimmedContent
    });

    // 获取完整的消息信息（包含发送者信息）
    const fullMessage = await Message.findById(message.id);
    const messageData = {
      ...fullMessage.toJSON(),
      sender: {
        id: userId.toString(),
        nickname: req.user.nickname || '未知用户',
        avatar_url: req.user.avatar_url
      },
      group: {
        id: group.id.toString(),
        group_name: group.group_name
      }
    };

    ResponseHelper.success(res, messageData, '消息发送成功');

    scheduleGroupWechatPush({
      userId,
      senderNickname: req.user.nickname,
      content: trimmedContent,
      region: group.group_name,
      logTag: '📱 [公众号推送-分群]',
      targetName: group.group_name
    });

  } catch (error) {
    console.error('向指定群组发送消息错误:', error);
    ResponseHelper.serverError(res, '发送消息失败', error);
  }
});

/**
 * 向所有群组发送消息（保留原有的全国总群发送功能，用于兼容）
 * POST /api/v1/chat/all-groups/messages
 */
router.post('/all-groups/messages', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { content, message_type = 'text' } = req.body;
    const trimmedContent = typeof content === 'string' ? content.trim() : '';

    // 验证输入
    if (!trimmedContent) {
      return ResponseHelper.validationError(res, ['消息内容不能为空']);
    }

    // 检查用户是否被禁言
    const isBanned = await UserPrisma.isChatBanned(userId);
    if (isBanned) {
      return ResponseHelper.forbidden(res, '您已被禁言，无法发送消息');
    }

    // 获取所有群聊（排除私聊）
    const groupsResult = await ChatGroup.getGroupList({ page: 1, pageSize: 100 });
    const groups = groupsResult.data;

    if (groups.length === 0) {
      return ResponseHelper.validationError(res, ['暂无可发送的群组']);
    }

    try {
      await ensureChatQuota(userId, groups.length);
    } catch (error) {
      return handleQuotaError(error, res);
    }

    // 更新用户定位信息
    const { user: refreshedUser } = await UserLocationHelper.updateUserLocationFromRequest(req, req.user);
    if (refreshedUser) {
      req.user = refreshedUser;
    }

    // 向所有群组发送消息
    const sentMessages = [];
    const regionTargets = new Map();
    for (const group of groups) {
      try {
        // 自动加入群组（如果尚未加入）
        await GroupMember.create({
          group_id: group.id,
          user_id: userId,
          role: 'member'
        });
      } catch (error) {
        // 如果已经是成员，忽略错误
        if (!error.message.includes('已经是群组成员')) {
          console.warn(`自动加入群组 ${group.id} 失败:`, error.message);
        }
      }

      // 发送消息到该群组，添加全国总群广播标识
      const message = await Message.create({
        group_id: group.id,
        sender_id: userId,
        message_type,
        content: trimmedContent,
        broadcast_tag: 'national_broadcast'
      });

      sentMessages.push(message);

      const regionKey = IpLocationService.mapRegionToProvinceKey(group.group_name) || '全国';
      if (!regionTargets.has(regionKey)) {
        regionTargets.set(regionKey, {
          region: regionKey,
          targetName: group.group_name
        });
      }
    }

    if (!regionTargets.has('全国')) {
      regionTargets.set('全国', {
        region: '全国',
        targetName: '全国总群'
      });
    }

    // 返回第一条消息作为代表（前端显示用）
    const firstMessage = sentMessages[0];
    const messageWithSender = await Message.findById(firstMessage.id);

    // 先响应给用户
    ResponseHelper.success(res, {
      ...messageWithSender.toJSON(),
      broadcast_count: sentMessages.length,
      message: `消息已发送到${sentMessages.length}个群组`
    }, `消息已成功发送到${sentMessages.length}个群组`);

    // 异步发送公众号推送通知,不阻塞响应
    regionTargets.forEach(({ region: regionKey, targetName: targetLabel }) => {
      scheduleGroupWechatPush({
        userId,
        senderNickname: req.user.nickname,
        content: trimmedContent,
        region: regionKey,
        logTag: '📱 [公众号推送]',
        targetName: targetLabel
      });
    });

  } catch (error) {
    console.error('向所有群组发送消息错误:', error);
    ResponseHelper.serverError(res, '向所有群组发送消息失败', error);
  }
});

// ==================== 私聊相关接口 ====================

/**
 * 发起私聊
 * POST /api/v1/chat/private/start/:userId
 */
router.post('/private/start/:userId', authenticateToken, async (req, res) => {
  try {
    const currentUserId = req.user.id;
    const targetUserId = parseInt(req.params.userId);

    // 验证目标用户ID
    if (!targetUserId || targetUserId === currentUserId) {
      return ResponseHelper.validationError(res, ['无效的用户ID']);
    }

    // 创建或获取私聊群组
    const privateChat = await ChatGroup.createOrGetPrivateChat(currentUserId, targetUserId);

    ResponseHelper.success(res, privateChat.toJSON(), '私聊创建成功');
  } catch (error) {
    console.error('发起私聊错误:', error);
    ResponseHelper.serverError(res, '发起私聊失败', error);
  }
});

/**
 * 获取私聊列表
 * GET /api/v1/chat/private/list
 */
router.get('/private/list', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    const privateChats = await ChatGroup.getUserPrivateChats(userId);

    ResponseHelper.success(res, privateChats, '获取私聊列表成功');
  } catch (error) {
    console.error('获取私聊列表错误:', error);
    ResponseHelper.serverError(res, '获取私聊列表失败', error);
  }
});

/**
 * 获取与某用户的私聊消息
 * GET /api/v1/chat/private/:userId/messages
 */
router.get('/private/:userId/messages', authenticateToken, async (req, res) => {
  try {
    const currentUserId = req.user.id;
    const targetUserId = parseInt(req.params.userId);
    const { page = 1, pageSize = 50, lastMessageId } = req.query;

    // 验证目标用户ID
    if (!targetUserId || targetUserId === currentUserId) {
      return ResponseHelper.validationError(res, ['无效的用户ID']);
    }

    // 获取或创建私聊群组
    const privateChat = await ChatGroup.createOrGetPrivateChat(currentUserId, targetUserId);

    // 获取私聊消息
    const result = await Message.getGroupMessages(privateChat.id, {
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      lastMessageId: lastMessageId ? parseInt(lastMessageId) : undefined
    });

    ResponseHelper.success(res, result, '获取私聊消息成功');
  } catch (error) {
    console.error('获取私聊消息错误:', error);
    ResponseHelper.serverError(res, '获取私聊消息失败', error);
  }
});

/**
 * 发送私聊消息
 * POST /api/v1/chat/private/:userId/messages
 */
router.post('/private/:userId/messages', authenticateToken, async (req, res) => {
  try {
    const currentUserId = req.user.id;
    const targetUserId = parseInt(req.params.userId);
    const { content, message_type = 'text' } = req.body;

    // 验证目标用户ID
    if (!targetUserId || targetUserId === currentUserId) {
      return ResponseHelper.validationError(res, ['无效的用户ID']);
    }

    // 验证消息内容
    if (!content || content.trim() === '') {
      return ResponseHelper.validationError(res, ['消息内容不能为空']);
    }

    // 检查用户是否被禁言
    const isBanned = await UserPrisma.isChatBanned(currentUserId);
    if (isBanned) {
      return ResponseHelper.forbidden(res, '您已被禁言，无法发送消息');
    }

    try {
      await ensureChatQuota(currentUserId, 1);
    } catch (error) {
      return handleQuotaError(error, res);
    }

    // 获取或创建私聊群组
    const privateChat = await ChatGroup.createOrGetPrivateChat(currentUserId, targetUserId);

    // 更新用户定位信息
    const { user: refreshedUser } = await UserLocationHelper.updateUserLocationFromRequest(req, req.user);
    if (refreshedUser) {
      req.user = refreshedUser;
    }

    // 创建消息
    const message = await Message.create({
      group_id: privateChat.id,
      sender_id: currentUserId,
      message_type,
      content: content.trim()
    });

    // 获取完整的消息信息（包含发送者信息）
    const fullMessage = await Message.findById(message.id);
    const messageData = {
      ...fullMessage.toJSON(),
      sender: {
        id: currentUserId.toString(),
        nickname: req.user.nickname || '未知用户',
        avatar_url: req.user.avatar_url
      }
    };

    ResponseHelper.success(res, messageData, '发送私聊消息成功');
  } catch (error) {
    console.error('发送私聊消息错误:', error);

    if (error.message === '聊天消息额度不足') {
      return ResponseHelper.forbidden(res, '聊天消息额度不足，请购买聊天套餐');
    }

    ResponseHelper.serverError(res, '发送私聊消息失败', error);
  }
});

/**
 * 获取私聊新消息（轮询接口）
 * GET /api/v1/chat/private/:userId/new-messages
 */
router.get('/private/:userId/new-messages', authenticateToken, async (req, res) => {
  try {
    const currentUserId = req.user.id;
    const targetUserId = parseInt(req.params.userId);
    const { lastMessageId = 0 } = req.query;

    // 验证目标用户ID
    if (!targetUserId || targetUserId === currentUserId) {
      return ResponseHelper.validationError(res, ['无效的用户ID']);
    }

    // 获取私聊群组（如果不存在则不创建，直接返回空）
    const currentUserIdNum = Number(currentUserId);
    const smallerId = Math.min(currentUserIdNum, targetUserId);
    const largerId = Math.max(currentUserIdNum, targetUserId);
    const privateUserIds = `${smallerId}_${largerId}`;

    const existingGroup = await prisma.chat_groups.findFirst({
      where: {
        group_type: 'private',
        private_user_ids: privateUserIds
      }
    });

    if (!existingGroup) {
      return ResponseHelper.success(res, [], '暂无新消息');
    }

    // 获取新消息
    const newMessages = await Message.getNewMessages(existingGroup.id, parseInt(lastMessageId));

    ResponseHelper.success(res, newMessages, '获取私聊新消息成功');
  } catch (error) {
    console.error('获取私聊新消息错误:', error);
    ResponseHelper.serverError(res, '获取私聊新消息失败', error);
  }
});

/**
 * 获取未读私信数量统计
 * GET /api/v1/chat/private/unread-count
 */
router.get('/private/unread-count', authenticateToken, async (req, res) => {
  try {
    const currentUserId = req.user.id;
    const { lastCheckTime } = req.query; // 前端传递最后查看私信的时间

    // 获取用户的所有私聊群组
    const privateChats = await ChatGroup.getUserPrivateChats(currentUserId);

    let totalUnreadCount = 0;
    const unreadDetails = [];

    // 如果没有提供lastCheckTime，使用1小时前作为默认值
    const checkTime = lastCheckTime ? new Date(parseInt(lastCheckTime)) : new Date(Date.now() - 60 * 60 * 1000);

    for (const chat of privateChats) {
      // 获取该私聊群组中在指定时间之后且不是当前用户发送的消息
      const unreadMessages = await prisma.messages.findMany({
        where: {
          group_id: parseInt(chat.id),
          sender_id: { not: BigInt(currentUserId) },
          created_at: { gt: checkTime } // 只查询指定时间之后的消息
        },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true
            }
          }
        },
        orderBy: { created_at: 'desc' },
        take: 10 // 限制查询数量，避免性能问题
      });

      if (unreadMessages.length > 0) {
        const unreadCount = Math.min(unreadMessages.length, 99); // 最多显示99+
        totalUnreadCount += unreadCount;

        unreadDetails.push({
          chatId: chat.id,
          otherUserId: chat.other_user?.id,
          otherUserNickname: chat.other_user?.nickname,
          unreadCount: unreadCount,
          lastMessage: {
            id: unreadMessages[0].id.toString(),
            content: unreadMessages[0].content,
            created_at: unreadMessages[0].created_at,
            sender: {
              id: unreadMessages[0].users?.id?.toString(),
              nickname: unreadMessages[0].users?.nickname
            }
          }
        });
      }
    }

    ResponseHelper.success(res, {
      totalUnreadCount: Math.min(totalUnreadCount, 99), // 最多显示99+
      unreadDetails
    }, '获取未读私信数量成功');
  } catch (error) {
    console.error('获取未读私信数量错误:', error);
    ResponseHelper.serverError(res, '获取未读私信数量失败', error);
  }
});

module.exports = router;
